package com.tte.common.utils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.*;

/**
 * Object Map List转换工具类
 */
@Component
public class ConvertObjMapList {

    /**
     * 将Object对象里面的属性和值转化成Map对象
     * @Param obj 需要转换的对象
     * @return: 转换完成的Map
     */
    public static Map<String, Object> objToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<String,Object>();
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object o = field.get(obj);
            map.put(fieldName, o);
        }
        return map;
    }

    /**
     * 将List<Object>对象里面的属性和值转化成List<Map>对象
     * @Param obj 需要转换的对象集合
     * @return: 转换完成的List<Map>
     */
    public static List<Map<String, Object>> listObjToListMap(List<?> list) throws IllegalAccessException {
        List<Map<String, Object>> listMap=new ArrayList<>();
        for (Object obj : list) {
            listMap.add(objToMap(obj));
        }
        return listMap;
    }

    /**
     * object转List，反射需字段为public
     * @Author: DongWH
     * @Date: 2021/9/21 15:53
     * @Param vClass value类型
     * @return:
     */
    public static <V> List<Map<String,V>> objConvertListMap(Object obj, Class<V> vClass) throws IllegalAccessException {
        List<Map<String, V>> result = new ArrayList<>();
        if (obj instanceof List<?>) {
            for (Object o : (List<?>) obj) {
                Map<String, V> map = new HashMap<>(16);
                Class<?> oClass = o.getClass();
                for (Field field : oClass.getDeclaredFields()) {
                    field.setAccessible(true);
                    String key = field.getName();
                    Object value = field.get(key);
                    if (value == null) {
                        value = "";
                    }
                    map.put(key, vClass.cast(value));
                }
                result.add(map);
            }
            return result;
        }
        return null;
    }

    /**
     * 字典树转Map，只保留code Value
     * @Author: DongWH
     * @Date: 2021/9/21 15:53
     * @Param vClass value类型
     * @return:
     */
    public static <T> Map<String,T> objConvertMap(Object obj, Class<?> vClass) throws IllegalAccessException {
        Map<String, T> resultMap = new HashMap<>();
        if (obj instanceof List<?>) {
            for (Object o : (List<?>) obj) {
                Map<String, T> map = new HashMap<>(16);
                String k = "";
                T v = null;
                resultMap.put(k,v);
            }
            return resultMap;
        }
        return null;
    }


}
